package utils

import (
	"fresh-shop-gin/config"
	"os"
	"path/filepath"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *zap.Logger

// 基于配置初始化日志
func InitLogger(cfg *config.Config) {
	
	// 确保日志目录存在
	if err := os.MkdirAll(filepath.Dir(cfg.Log.Path), 0755); err != nil {
		panic(err)
	}

	// 配置日志级别
	logLevel := map[string]zapcore.Level{
		"debug": zapcore.DebugLevel,
		"info":  zapcore.InfoLevel,
		"warn":  zapcore.WarnLevel,
		"error": zapcore.ErrorLevel,
	}[cfg.Log.Level]

	// 日志轮转配置
	logRotate := &lumberjack.Logger{
		Filename:   cfg.Log.Path,
		MaxSize:    cfg.Log.Rotation.MaxSize,
		MaxBackups: cfg.Log.Rotation.MaxBackups,
		MaxAge:     cfg.Log.Rotation.MaxAge,
		Compress:   cfg.Log.Rotation.Compress,
	}

	// 创建核心配置
	cores := []zapcore.Core{
		createFileCore(logRotate, logLevel),
	}

	// 开发环境添加控制台输出
	if cfg.Log.Env == "development" {
		cores = append(cores, createConsoleCore(logLevel))
	}

	// 创建核心组合
	core := zapcore.NewTee(cores...)

	// 构建Logger
	Logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1), zap.AddStacktrace(zapcore.ErrorLevel))

	// 替换全局的zap logger
	zap.ReplaceGlobals(Logger)
}

// 创建文件输出核心
func createFileCore(logRotate *lumberjack.Logger, logLevel zapcore.Level) zapcore.Core {
	encoder := getJSONEncoder()
	return zapcore.NewCore(
		encoder,
		zapcore.AddSync(logRotate),
		zap.NewAtomicLevelAt(logLevel),
	)
}

// 创建控制台输出核心
func createConsoleCore(logLevel zapcore.Level) zapcore.Core {
	encoder := getConsoleEncoder()
	return zapcore.NewCore(
		encoder,
		zapcore.AddSync(os.Stdout),
		zap.NewAtomicLevelAt(logLevel),
	)
}

// JSON格式编码器（用于文件输出）
func getJSONEncoder() zapcore.Encoder {
	return zapcore.NewJSONEncoder(zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	})
}

// 控制台友好格式编码器（用于开发环境）
func getConsoleEncoder() zapcore.Encoder {
	return zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalColorLevelEncoder,
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"),
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	})
}

func GetLogger() *zap.Logger {
	return Logger
}